class Solution(object):

    def buildTree(self, inorder, postorder):
        """
        :type inorder: List[int]
        :type postorder: List[int]
        :rtype: TreeNode
        """
        if (len(inorder)) == 0:
            return None
        self.inorder_index = self.build_index(inorder)
        self.inorder = inorder
        self.postorder = postorder
        return self.helper(0, len(inorder) - 1, 0, len(postorder) - 1)

    def helper(self, inorder_start, inorder_end, postorder_start, post_end):
        if postorder_start > post_end:
            return None

        root_val = self.postorder[post_end]
        root = TreeNode(root_val)

        inorder_index = self.inorder_index[root_val]
        length = inorder_index - inorder_start

        root.left = self.helper(inorder_start, inorder_index - 1, postorder_start, postorder_start + length - 1)
        root.right = self.helper(inorder_index + 1, inorder_end, postorder_start + length, post_end - 1)
        return root

    def build_index(self, nodes):
        return {nodes[i]:i for i in range(len(nodes))}